﻿using System;
using System.Configuration;
using System.Data;
using System.Data.OracleClient;
using TimeTableEasy.src.Core;
using System.Windows;
using System.Threading;

namespace TimeTableEasy.src.Database
{

    class OracleConnector : Singleton<OracleConnection>
    {
        private String connectionString = "Data Source=(DESCRIPTION="
                                                    + "(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=94.23.47.97)(PORT=1521)))"
                                                    + "(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=ORCL)));"
                                                    + "User Id=TimeTableasy_app;Password=mpTimeTableasy_app";

        private static OracleConnection connection;
        private static OracleCommand query;
        private static bool m_Offline = false;

        public OracleConnector()
        {
            try
            {
                connection = Singleton<OracleConnection>.Instance;
                if (connection.State != ConnectionState.Open)
                {
                    connection.ConnectionString = this.connectionString;
                    connection.Open();
                }
            }
            catch (OracleException ex)
            {
                switch (ex.Code)
                {
                    case 12170:
                    case 12560:
                        m_Offline = true;
                        break;
                    default:
                        LogMgr.ERROR_LOG("DATABASE ERROR: " + ex.Message.ToString());
                        break;
                }
            }
            catch (Exception ex)
            {
                LogMgr.ERROR_LOG("DATABASE ERROR: " + ex.Message.ToString());
            }
        }

        public static OracleDataReader Query(String request)
        {
            LogMgr.DEBUG_LOG("SQL REQUEST : "+request);
            OracleDataReader array;

            try
            {
                if (connection.State == ConnectionState.Closed)
                    connection.Open();

                query = new OracleCommand(request);
                query.Connection = connection;
                query.CommandType = System.Data.CommandType.Text;
                array = query.ExecuteReader();
            }
            catch (Exception ex)
            {
                array = null;
                LogMgr.ERROR_LOG("SQL REQUEST ERROR : " + ex.Message);
            }

            return array;        
        }

        public static bool Offline
        {
            get { return m_Offline; }
            set { m_Offline = value; }
        }

        ~OracleConnector()
        {

        }
    }
}
